<template>
  <el-drawer
      title="申请创建自己的空间"
      v-model="visible"
      width="50%"
      :destroy-on-close="true"
      @close="onCancel"
  >
    <el-form :model="form" ref="formRef" label-width="120px" class="styled-form">
      <!-- 空间名称 -->
      <el-form-item
          label="空间名称"
          prop="spaceName"
          :rules="[{ required: true, message: '请输入空间名称', trigger: 'blur' }]"
      >
        <el-input v-model="form.spaceName" placeholder="请输入空间名称"></el-input>
      </el-form-item>

      <!-- 空间类型 -->
      <el-form-item label="空间类型">
        <DropdownDictSelect v-model="form.spaceType" dict-name="SPACE_TYPE" />
      </el-form-item>

      <!-- 空间标签 -->
      <el-form-item label="空间标签">
        <el-input v-model="form.spaceTags" placeholder="请输入标签，以逗号分隔" />
      </el-form-item>

      <!-- 空间 Logo -->
      <el-form-item label="空间 Logo">
        <el-upload
            list-type="picture-card"
            :limit="1"
            :file-list="logoFileList"
            :before-upload="(file) => handleBeforeUpload(file, 'spaceLogo')"
            :on-remove="() => handleRemove('spaceLogo')"
        >
          <el-button type="primary" v-if="!form.spaceLogo">选择图片</el-button>
        </el-upload>
      </el-form-item>

      <!-- 空间背景图 -->
      <el-form-item label="空间背景图">
        <el-upload
            list-type="picture-card"
            :limit="1"
            :file-list="backgroundFileList"
            :before-upload="(file) => handleBeforeUpload(file, 'spaceBackground')"
            :on-remove="() => handleRemove('spaceBackground')"
        >
          <el-button type="primary" v-if="!form.spaceBackground">选择图片</el-button>
        </el-upload>
      </el-form-item>

      <!-- 是否付费 -->
      <el-form-item label="是否付费">
        <el-switch v-model="form.isFree" :active-value="false" :inactive-value="true" />
      </el-form-item>

      <!-- 会费 -->
      <el-form-item label="会费" v-if="!form.isFree">
        <el-input-number v-model="form.fee" :min="0" placeholder="请输入会费" />
      </el-form-item>

      <!-- 空间描述 -->
      <el-form-item label="空间描述">
        <el-input
            type="textarea"
            v-model="form.spaceDescription"
            placeholder="请输入空间描述"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <div class="drawer-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button type="primary" @click="testRequest">测试请求</el-button> <!-- 新增测试按钮 -->
      </div>
    </el-form>
  </el-drawer>
</template>

<script>
import {ref, watch, toRefs, onMounted} from 'vue';
import DropdownDictSelect from "@/components/dropdown/DropdownSelect.vue";
import {createSpace, testSpace} from "@/service/space/space.service";

export default {
  name: 'CreateSpaceDrawer',
  components: { DropdownDictSelect },
  props: {
    modelValue: {
      type: Boolean,
      required: true,
    },
  },
  emits: ['update:modelValue', 'close', 'save'],
  setup(props, { emit }) {
    const { modelValue } = toRefs(props);
    const visible = ref(modelValue.value);

    watch(modelValue, (newValue) => {
      visible.value = newValue;
    });

    watch(visible, (newValue) => {
      emit('update:modelValue', newValue);
    });

    const form = ref({
      spaceName: '',
      spaceType: 1,
      spaceTags: '',
      spaceLogo: '',
      spaceBackground: '',
      isFree: true,
      fee: null,
      spaceDescription: '',
    });

    const formRef = ref(null);


    // 图片文件
    const logoFile = ref(null);
    const backgroundFile = ref(null);
    const logoFileList = ref([]);
    const backgroundFileList = ref([]);

    const handleBeforeUpload = (file, field) => {
      if (field === 'spaceLogo') {
        logoFile.value = file;
        logoFileList.value = [{ url: URL.createObjectURL(file) }];
      } else if (field === 'spaceBackground') {
        backgroundFile.value = file;
        backgroundFileList.value = [{ url: URL.createObjectURL(file) }];
      }
      return false; // 阻止 el-upload 默认上传行为
    };
    const testRequest = () => {
      testSpace(
          null,
          (response) => {
            console.log("测试请求成功:", response);
          },
          (error) => {
            console.error("测试请求失败:", error);
          }
      );
    };
    const handleRemove = (field) => {
      if (field === 'spaceLogo') {
        logoFile.value = null;
        logoFileList.value = [];
      } else if (field === 'spaceBackground') {
        backgroundFile.value = null;
        backgroundFileList.value = [];
      }
    };

    const onSave = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          const formData = new FormData();

          // 将表单字段直接添加到 FormData
          formData.append("spaceName", form.value.spaceName);
          formData.append("spaceType", form.value.spaceType);
          formData.append("spaceTags", form.value.spaceTags);
          formData.append("isFree", form.value.isFree);
          formData.append("fee", form.value.fee || 0);
          formData.append("spaceDescription", form.value.spaceDescription);

          // 添加 logoFile 和 backgroundFile
          if (logoFile.value) {
            formData.append("spaceLogo", logoFile.value);
          }
          if (backgroundFile.value) {
            formData.append("spaceBackground", backgroundFile.value);
          }


          // 调用 createSpace 方法
          createSpace(formData,
              (response) => {
                console.log('创建空间成功:', response);
                emit('save', response.data);
                emit('update:modelValue', false); // 关闭 Drawer
              },
              (error) => {
                console.error('创建空间失败:', error);
              }
          );
        } else {
          console.log('表单验证失败');
        }
      });
    };


    const onCancel = () => {
      emit('update:modelValue', false);
    };

    return {
      visible,
      form,
      formRef,
      onSave,
      onCancel,
      handleBeforeUpload,
      handleRemove,
      logoFileList,
      backgroundFileList,testRequest
    };
  },
};
</script>

<style scoped>
.styled-form {
  max-width: 600px;
  margin: 0 auto;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.drawer-footer .el-button {
  margin-left: 10px;
}

.image-preview {
  width: 100px;
  height: 100px;
  margin-top: 10px;
  display: inline-block;
}
</style>
